#include "helicopter.h"
#include "footHelicopter.h"
#include "helicopterSkin.h"
#include "clamp.h"
#include "../framework.h"
#include <cmath>

const float Helicopter::maxSpeedx = 10.0f;
const float Helicopter::accelx = 0.5f;
const float Helicopter::maxSpeedy = 5.0f;
const float Helicopter::accely = 0.5f;
const float Helicopter::rotationAngle=0.02f;

Helicopter::Helicopter(Rectangle recSkin, Rectangle recThread,Rectangle recClamp)
	:SceneObject(recSkin){
    this->theta=0;
    this->speedy=0;
	this->addObject(HelicopterSkin::name(),new HelicopterSkin(Rectangle(0,0,0,0)));
	this->addObject(Thread::name(),new Thread(recThread,recClamp));
}

Helicopter::~Helicopter(){}

void Helicopter::draw(){
	Framework& fr = Framework::instance();
	Colorf oldColor = fr.pipeline.getLineColor();
	fr.pipeline.pushMatrix();
		(this->findObject(Thread::name())).draw();
		fr.pipeline.pushMatrix();
			fr.pipeline.translate(this->dimensions.centerX(),dimensions.centerY());
			fr.pipeline.escale(dimensions.width()/85, dimensions.height()/50);
			fr.pipeline.rotate(theta);
			(this->findObject(HelicopterSkin::name())).draw();
		fr.pipeline.popMatrix();
    fr.pipeline.popMatrix();
}

void Helicopter::timeStep(){
	HelicopterSkin& skin = dynamic_cast<HelicopterSkin&>(this->findObject(HelicopterSkin::name()));
	skin.timeStep();
    Thread& thread=dynamic_cast<Thread&>(this->findObject(Thread::name()));
    thread.timeStep();
    thread.findObject(Clamp::name()).move(speed,speedy);
    dimensions.translate(speed,speedy);
    thread.getDimensions().translate(speed,speedy);
}

void Helicopter::accelerateX(MotionVectorX dir){
	this->speed += Helicopter::accelx*dir;

	if(fabs(this->speed)>Helicopter::maxSpeedx){
		this->speed = Helicopter::maxSpeedx*dir;
	}else{
		this->theta += rotationAngle*dir;
	}
}

void Helicopter::move(float dx,float dy){
	SceneObject::move(dx,dy);
	Thread& thread=dynamic_cast<Thread&>(this->findObject(Thread::name()));
	thread.findObject(Clamp::name()).move(dx,dy);
	thread.getDimensions().translate(dx,dy);
}

void Helicopter::accelerateY(MotionVectorY dir){
	this->speedy += Helicopter::accely*dir;

	if(fabs(this->speedy)>Helicopter::maxSpeedy)
		this->speedy = Helicopter::maxSpeedy*dir;
}

void Helicopter::closeClamp(){
	Thread& thread=dynamic_cast<Thread&>(this->findObject(Thread::name()));
	thread.closeClamp();
}

void Helicopter::openClamp(){
	Thread& thread=dynamic_cast<Thread&>(this->findObject(Thread::name()));
	thread.openClamp();
}

void Helicopter::moveClamp(Thread::MotionVector dir){
	Thread& thread=dynamic_cast<Thread&>(this->findObject(Thread::name()));
	Clamp& clamp=dynamic_cast<Clamp&>(thread.findObject(Clamp::name()));
	if ((clamp.getDimensions().y1> this->dimensions.y2)&&(dir==Thread::UP))
        thread.moveClamp(dir);
    else if(dir==Thread::DOWN)
        thread.moveClamp(dir);
}
